package cn.wen.base.decoration;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import cn.wen.base.R;

/**
 * 使用LinearLayoutManager的分割线
 */

public class GridItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public GridItemDecoration(Context context, int drawableResId) {
        mDivider = ContextCompat.getDrawable(context, drawableResId);
    }

    public GridItemDecoration(Context context) {
        this(context, R.drawable.decoration_grid);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 留出空间来画分割线
        outRect.bottom = mDivider.getIntrinsicHeight();
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

        int right = mDivider.getIntrinsicWidth();
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;
            int spanCount = manager.getSpanCount();
            int position = parent.getChildLayoutPosition(view);
            if ((position + 1) % spanCount == 0) {
                right = 0;
            }
        }
        outRect.right = right;


    }

    @Override
    public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        // 循环画分割线
        drawHorizontal(canvas, parent);
        drawVertical(canvas, parent);
    }

    private void drawVertical(Canvas canvas, RecyclerView parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int left = childView.getRight();
            int right = childView.getRight() + mDivider.getIntrinsicWidth();
            int top = childView.getTop();
            int bottom = childView.getBottom();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
    }

    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int left = childView.getLeft();
            int right = childView.getRight() + mDivider.getIntrinsicWidth();
            int top = childView.getBottom();
            int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
    }
}
